package logic

import (
	"common/globals"
	"common/model"
	"context"
	"errors"
	user "user_srv/proto"
)

func (u *UserServer) CouponAdd(ctx context.Context, req *user.CouponAddRequest) (*user.CouponAddResponse, error) {
	var userinfo model.User
	err := userinfo.GetUserInfoById(int(req.Userid))
	if err != nil {
		return nil, err
	}
	if userinfo.ID == 0 {
		return nil, errors.New("请重新登录")
	}
	var couponInfo model.Coupon
	err = couponInfo.GetCouponInfoById(int(req.CouponId))
	if err != nil {
		return nil, err
	}
	if couponInfo.ID == 0 || couponInfo.Socket <= 0 {
		return nil, errors.New("该优惠券已经抢光啦")
	}
	var userCoupon model.UserCoupon
	err = userCoupon.GetCouponByCouponIdAndUserId(int(req.CouponId), int(req.Userid))
	if err != nil {
		return nil, err
	}
	if userCoupon.ID != 0 {
		return nil, errors.New("你已经领取过该优惠券 无法再次领取")
	}
	tx := globals.Db.Begin()
	userCouponAdd := model.UserCoupon{
		UserId:            int(req.Userid),
		CouponId:          int(req.CouponId),
		CouponPrice:       couponInfo.CouponPrice,
		HowMoneyAvailable: couponInfo.HowMoneyAvailable,
	}
	err = userCouponAdd.Create()
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	err = couponInfo.UpdateSocketById(int(req.CouponId), couponInfo.Socket-1)
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	tx.Commit()
	return &user.CouponAddResponse{Success: true}, nil
}
